package com.weixing.mall.provider.model.excel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.provider.service.IDepotExtraService;
import com.weixing.mall.provider.service.IProductStockDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * 仓库编码批量导入删除
 */
public class DepotSnImportDataListener extends AnalysisEventListener<DepotSnExcelData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DepotSnImportDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    List<DepotSnExcelData> list = new ArrayList<>();

    private IDepotExtraService depotExtraService;

    private IProductStockDetailsService productStockDetailsService;

    public DepotSnImportDataListener(IDepotExtraService depotExtraService,IProductStockDetailsService productStockDetailsService){
           this.depotExtraService = depotExtraService;
          this.productStockDetailsService = productStockDetailsService;
    }

    @Override
    public void invoke(DepotSnExcelData data, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        //这里用不上
        /*if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }*/
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        handleData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 处理数据
     */
    void handleData() {
        LOGGER.info("{}条数据！", list.size());
        if(list.size() ==0 ){
            throw new BusinessException("导入数据为空");
        }
        if(list.size() > 0){
            //导入删除仓库编码
            for (DepotSnExcelData ds:list){
                if(ObjectUtil.isNotEmpty(ds) && StrUtil.isNotEmpty(ds.getDepotSn())){
                    depotExtraService.delByDepotSn(ds.getDepotSn());
                    productStockDetailsService.delByDepotSn(ds.getDepotSn());
                }
            }
        }
        LOGGER.info("删除完成！");
    }
}
